package esqeee.xieqing.com.huangrs.doAction.api;

import com.xieqing.codeutils.util.LogUtils;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;

public class MD5Utils {

    private static String secret = "VMPJP743KP42KVQ71OPKRZJX2OI8HC";
    /**
     * 得到签名
     *
     * @param content 参数集合,不含密钥secret
     * @return sign 签名
     */
    public static String getSign(String content) {
        byte[] md5Digest;
        // Md5加密得到sign
        md5Digest = getMd5Digest(content + secret);
        return byte2hex(md5Digest);
    }

    /**
     * 获取md5信息摘要
     *
     * @param data 需要加密的字符串
     * @return bytes 字节数组
     */
    private static byte[] getMd5Digest(String data) {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
        } catch (GeneralSecurityException gse) {
            LogUtils.e("生成签名错误", gse);
        }
        return bytes;
    }

    /**
     * 将字节数组转化为16进制
     *
     * @param bytes 字节数组
     * @return sign 签名
     */
    private static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (byte aByte : bytes) {
            String hex = Integer.toHexString(aByte & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }
}
